package model.objects;

import java.awt.Graphics;
import java.awt.Rectangle;

import javax.swing.JPanel;

import model.general.Location;
import model.move.IMove;
import model.move.MoveBoat;
import model.observer.Obsever;
import model.option.Option;

public class Boat extends Sprites implements IAnimateMainActor{
	private IMove move;
	private IAnimateSubActor hook;
	private JPanel pnl;
	private boolean isMoveLeft = false;

	private static final String DEFAUT_IMG_BOAT_LEFT = "boat-left.png";
	private static final String DEFAUT_IMG_BOAT_RIGHT = "boat-right.png";

	public Boat(int x, int y, String srcImg, JPanel pnl) {
		super(x, y, srcImg);
		this.move = new MoveBoat(location);
		this.pnl = pnl;
	}
	
	@Override
	public void show(Graphics g) {
		g.drawImage(img, location.getX(), location.getY(), null);
	}

	@Override
	public void moveLeft() {
		if (!hasOutPanel()){
			isMoveLeft = true;
			isChangeImage();
			move.moveLeft();
			hook.updateLocation(location);
		}
	}

	@Override
	public void moveRight() {
		if (!hasOutPanel()){
			isMoveLeft = false;
			isChangeImage();
			move.moveRight();
			hook.updateLocation(location);
		}
	}
	
	private void isChangeImage() {
		// TODO Auto-generated method stub
		if (isMoveLeft == true && srcImg.equals(DEFAUT_IMG_BOAT_RIGHT)) {
			srcImg = DEFAUT_IMG_BOAT_LEFT;
			img = loadImage.getbufferImage(srcImg);
		}
		if (isMoveLeft == false && srcImg.equals(DEFAUT_IMG_BOAT_LEFT)) {
			srcImg = DEFAUT_IMG_BOAT_RIGHT;
			img = loadImage.getbufferImage(srcImg);
		}
	}
	
	public boolean hasOutPanel() {
		int min = this.pnl.getX();
		int max = this.pnl.getX() + this.pnl.getWidth() - this.width;
		if ((location.getX() < min)) {
			this.location.setX(min);
			return true;
		}
		if ((location.getX() > max)) {
			this.location.setX(max);
			return true;
		}
		return false;
	}

	@Override
	public void addObsever(IAnimateSubActor obsever) {
		hook = obsever;
	}

	@Override
	public void notifyObsever() {
		hook.updateLocation(location);
	}

	@Override
	public void removeObsever(IAnimateSubActor obsever) {
		hook = null;
	}

	@Override
	public Location getLocation() {
		return location;
	}

	@Override
	public void addOption(Option option) {
		option.addOption(this);
	}

	@Override
	public IAnimateSubActor getHook() {
		return hook;
	}

	@Override
	public void setHook(IAnimateSubActor hook) {
		//remove observer cu
		removeObsever(hook);
		//gan hook = hook moi
		this.hook = hook;
		//add observer moi
		addObsever(hook);
	}

	@Override
	public int getWidth() {
		return width;
	}

	@Override
	public int getHeight() {
		return height;
	}

	@Override
	public Rectangle getBoundingBox() {
		return location.getBounds(width, height);
	}
}
